import { checkBeforeInsert } from '@/utils/helpers'
import { v4 as uuid } from 'uuid'
import store from '@/store'
import { insertElementAfterBlock } from '@/utils/dom'
import { uploadFile, saveFlowChartXml, getFlowChartXml } from '@/api'
import { Message } from 'element-ui'
import {refreshFigureNumbers} from '../image/figureSetting'

tinymce.PluginManager.add('chart', function (editor) {
  let selectedChartImg = null
  // 编辑流程图
  var editChart = function(dbClicked = false) {
    const sel = editor.selection.getContent()
    // 点击到了流程图的img
    var path = /\<img(.*?)data-drawio-xml="(.*?)" \/>/g
    const path2 = /data-drawio-xml="(.*?)"/g
    if (sel.search(path) === 0) {
      sel.replace(path2, async function ($0, $1) {
        // xml以参数形式传递，可能会过大引起报错, 所以保存在localstorage中
        // 将图形保存在localstorage中,drawio页面初始化后可以使用
        if ($1?.length > 0) {
          try {
            const xmlContent = await getFlowChartXml($1)
            if (xmlContent) {
              localStorage.setItem('drawio-initial-data-xml', xmlContent)
              selectedChartImg = editor.selection.getNode()
              openDialog('1')
            } else {
              Message.error('流程图数据获取失败')
            }
          } catch (error) {
            Message.error('流程图数据获取失败')
          }
        }
      })
    } else if (!dbClicked) {
      openDialog('0')
    }
  }
  var openDialog = function (editXml) {
    if (!checkBeforeInsert('chart')) return
    const node = editor.selection.getNode()
    if (node.dataset?.type === 'item_list' || editor.dom.getParent(node, 'p.item_list')) {
      return Message.warning({
        message: `列项中暂不支持插入流程图`,
        showClose: true
      })
    }

    var baseURL = tinymce.baseURL + '/tinymce/plugins/chart/index.html'
    // var baseURL = 'http://localhost:3000'
    const { clientWidth, clientHeight } = editor.getDoc().documentElement
    return editor.windowManager.openUrl({
      title: '插入流程图',
      size: 'large',
      width: clientWidth,
      height: clientHeight,
      url: `${baseURL}?v=1000dev=0&initialFormat=xml&offline=1&editXml=${editXml}`,
      buttons: [
        {
          type: 'cancel',
          text: 'Close'
        },
        {
          type: 'custom',
          text: 'Save',
          name: 'save',
          primary: true
        }
      ],
      onAction: function (api, details) {
        switch (details.name) {
          case 'save':
            // 以图片格式保存
            api.sendMessage({
              type: 'export-chart-img'
            })
            // 以svg格式保存
            // api.sendMessage('export-chart-svg')
            break
          default:
            break
        }
      }
    })
  }

  // 点击页面中的流程图片，打开编辑
  editor.on('dblclick', () => editChart(true))

  const icon = `
    <svg width="24" height="25" viewBox="0 0 24 25" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g transform="translate(-1102.000000, -161.000000)" fill-rule="nonzero"> <g transform="translate(16.000000, 149.500000)"> <g transform="translate(190.000000, 8.000000)"> <g transform="translate(896.000000, 3.500000)"> <rect fill="#000000" opacity="0" x="0" y="0.5" width="24" height="24"></rect> <path d="M20.5721462,15.48799 L19.5624668,15.48799 L19.5624668,12.3348476 C19.5624668,11.8911004 19.2027352,11.5313688 18.758988,11.5313688 L12.9683113,11.5313688 L12.9683113,9.5115835 L14.3078691,9.5115835 C14.7516163,9.5115835 15.1113479,9.15185189 15.1113479,8.70810472 L15.1113479,4.75190998 C15.1113479,4.3081628 14.7516163,3.9484312 14.3078691,3.9484312 L10.3514611,3.9484312 C9.90771396,3.9484312 9.54798235,4.3081628 9.54798235,4.75190998 L9.54798235,8.70831796 C9.54798235,9.15206513 9.90771396,9.51179674 10.3514611,9.51179674 L11.361567,9.51179674 L11.361567,11.531582 L5.57089034,11.531582 C5.12714316,11.531582 4.76741155,11.8913136 4.76741155,12.3350608 L4.76741155,15.4882033 L3.42785378,15.4882033 C2.98410661,15.4882033 2.624375,15.8479349 2.624375,16.291682 L2.624375,20.24809 C2.624375,20.6918372 2.98410661,21.0515688 3.42785378,21.0515688 L7.38426176,21.0515688 C7.82800894,21.0515688 8.18774054,20.6918372 8.18774054,20.24809 L8.18774054,16.2914688 C8.18774054,15.8477216 7.82800894,15.48799 7.38426176,15.48799 L6.37415588,15.48799 L6.37415588,13.1383264 L11.361567,13.1383264 L11.361567,15.48799 L10.0220092,15.48799 C9.57826207,15.48799 9.21853047,15.8477216 9.21853047,16.2914688 L9.21853047,20.2478768 C9.21853047,20.691624 9.57826207,21.0513556 10.0220092,21.0513556 L13.9784172,21.0513556 C14.4221644,21.0513556 14.781896,20.691624 14.781896,20.2478768 L14.781896,16.2914688 C14.781896,15.8477216 14.4221644,15.48799 13.9784172,15.48799 L12.9683113,15.48799 L12.9683113,13.1383264 L17.9557225,13.1383264 L17.9557225,15.48799 L16.6157382,15.48799 C16.1719911,15.48799 15.8122595,15.8477216 15.8122595,16.2914688 L15.8122595,20.2478768 C15.8122595,20.691624 16.1719911,21.0513556 16.6157382,21.0513556 L20.5721462,21.0513556 C21.0158934,21.0513556 21.375625,20.691624 21.375625,20.2478768 L21.375625,16.2914688 C21.375625,15.8477216 21.0158934,15.48799 20.5721462,15.48799 Z M11.1549399,5.55517552 L13.5046036,5.55517552 L13.5046036,7.90483918 L11.1549399,7.90483918 L11.1549399,5.55517552 Z M6.58099622,19.4446112 L4.23111932,19.4446112 L4.23111932,17.0947343 L6.58078298,17.0947343 L6.58078298,19.4446112 L6.58099622,19.4446112 Z M13.1751517,19.4446112 L10.8252748,19.4446112 L10.8252748,17.0947343 L13.1749384,17.0947343 L13.1749384,19.4446112 L13.1751517,19.4446112 Z M19.7688807,19.4446112 L17.4190038,19.4446112 L17.4190038,17.0947343 L19.7686674,17.0947343 L19.7686674,19.4446112 L19.7688807,19.4446112 Z" id="形状" fill="#323333"></path> </g> </g> </g> </g> </g> </svg>
  `
  // 增加流程图图标
  editor.ui.registry.addIcon('chart-icon', icon)

  const base64ToBlob = (dataUrl) => {
    const arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1]
    const bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while(n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: mime })
  }

  window.addEventListener('message', function(e) {
    if (e?.data?.stpAction === 'insertFlowChart') {
      // 新增流程图
      const blob = base64ToBlob(e.data.src)
      const formData = new FormData()
      formData.append('file', blob, '_')
      try {
        uploadFile(formData).then(async ({ data }) => {
          const imgUrl = window.location.origin + '/prod-api/editor/file/download/' + data
          const { editXml, xml, width, height } = e.data
          const param = editXml ? { id: selectedChartImg.drawioXml, xmlContent: xml } : { xmlContent: xml }
          const xmlId = await saveFlowChartXml(param)
          const node = editor.selection?.getNode?.() || selectedChartImg
          if (editXml) {
            // 编辑流程图
            editor.dom.setAttribs(node, {
              src: imgUrl,
              'data-drawio-xml': xmlId,
              'data-width': width,
              'data-height': height,
              style: `width: ${width}px;`
            })
            selectedChartImg = null
            return
          }
          // 附录中的图编号不一样
          var annexParent = editor.dom.getParent(node, '.page-sheet.annex'), annexNumber = null,
            introductionParent = editor.dom.getParent(node, '.page-sheet.introduction'), className = ''
          if (annexParent) {
            annexNumber =  annexParent.querySelector('[data-annex-number]')?.dataset.annexNumber
            className = 'figure-annex'
          } else if (introductionParent) {
            className = 'figure-introduction'
          }
          const innerHTML = `
            <p class="image-wrapper">
              <img class="data-content-image" src="${imgUrl}" data-drawio-xml="${xmlId}" alt="" data-width="${width}" data-height="${height}" style="width: ${width}px;">
            </p>
            <p class="data-content-image-caption zh" data-id="${uuid()}"${annexNumber ? ` data-figure-annex-number="${annexNumber}"` : ''}>图题</p>
            ${store.getters.languageType === 'both' ?
              `<p class="data-content-image-caption en" data-id="${uuid()}"${annexNumber ? ` data-figure-annex-number="${annexNumber}"` : ''}>xxx</p>`
              : ''}
          `
          let config = {
            class: 'flow-chart data-content-image-wrapper ' + className,
            'data-type': 'figure',
            'data-block-id': uuid(),
            'data-id': uuid()
          }
          if (annexNumber) {
            config['data-figure-annex-number'] = annexNumber
          }
          const imgWrapper = editor.dom.create('div', config)
          imgWrapper.innerHTML = innerHTML
          insertElementAfterBlock(imgWrapper, editor)
          setTimeout(() => {
            // 刷新全文图编号
            refreshFigureNumbers(editor)
          }, 200)
        })
      } catch (error) {
        console.error(error)
      }
    }
  })
  var isNullable = function (a) {
    return a === null || a === undefined
  }
  var isNonNullable = function (a) {
    return !isNullable(a)
  }
  var getSelectedFormula = function (elm) {
    return elm ? editor.dom.getParent(elm, 'div.flow-chart[data-type="figure"]') :  null
  }
  var getSelectedImage = function (editor) {
    var imgElm = editor.selection.getNode()
    if (imgElm && (imgElm.nodeName !== 'IMG')) {
      return null
    }
    return imgElm
  }
  return (
    editor.ui.registry.addToggleButton('chart', {
      icon: 'chart-icon',
      tooltip: '流程图',
      onAction: function () {
        editChart()
      },
      onSetup: function (buttonApi) {
        buttonApi.setActive(isNonNullable(getSelectedFormula(getSelectedImage(editor))))
        return editor.selection.selectorChangedWithUnbind(
          'div.flow-chart[data-type="figure"]',
          buttonApi.setActive
        ).unbind
      }
    }),
    {
      getMetadata: function () {
        return {
          name: '流程图',
          url: 'http://sfrj.cn'
        }
      }
    }
  )
})

